package com.whjfxx.terminal.commons;

import com.whjfxx.terminal.enums.ResultEnum;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import lombok.EqualsAndHashCode;

import java.io.Serializable;

/**
 * Created by b.c on 20210507
 */
@Data
@EqualsAndHashCode(callSuper = false)
public class Result<T> implements Serializable {

    /**
     * 状态码
     */
    private String code;

    /**
     * 信息
     */
    private String msg;

    /**
     * T
     */
    private T data;

    public Result() {
    }

    public Result(ResultEnum resultEnum) {
        this.code = resultEnum.code;
        this.msg = resultEnum.msg;
    }

    public Result(ResultEnum resultEnum, T data) {
        this.code = resultEnum.code;
        this.msg = resultEnum.msg;
        this.data = data;
    }

    @JsonIgnore
    public boolean isSuccess() {
        return ResultEnum.success.code.equals(this.code);
    }

    @JsonIgnore
    public T unwrap() {
        if (this.isSuccess()) {
            return this.data;
        }
        return null;
    }

    public static <T> Result<T> success() {
        return new Result<T>(ResultEnum.success);
    }

    public static <T> Result<T> success(T data) {
        return new Result<>(ResultEnum.success, data);
    }

    public static <T> Result<T> fail() {
        return new Result<T>(ResultEnum.fail);
    }

    public static <T> Result<T> fail(String msg) {
        Result<T> result = new Result<T>(ResultEnum.fail);
        result.setMsg(msg);
        return result;
    }


    public static <T> Result<T> error() {
        return new Result<T>(ResultEnum.error);
    }

    public static <T> Result<T> loginTimeout() {
        return new Result<T>(ResultEnum.login_timeout);
    }
}
